<?php
namespace app\cli_app\controller;
// 对接某物流公司单据信息

use think\Cache;
use think\Log;
use think\Controller;
use GuzzleHttp\Client;

class GetIntData extends Controller {
    public function save_data($data) {
        // 获取单据数据

        // 对接数据转换

        // 检查单据是否已保存

        // 存在就先删除单据,再保存

        // 保存之前检查客户,客户的联系人(项目),等其他编码是否已存在
        // 不存在就插入

        // 返回失败或成功
    }

    public function get_data($beg_date, $end_date) {
        $timestamp = get_milli_second();
        $secretKey = 'JtWjG0N8YsiWmDtDvkTGNi0mdtNWiZJNYutZ';
        $sign_arr = [
            'accessKey' => 'qZjkUKQS7Sqszzpx2j',
            'startDate' => $beg_date,
            'endDate' => $end_date,
        ];
        ksort($sign_arr);
        $temp_str = '';
        foreach ($sign_arr as $key => $val) {
            $temp_str .= $key . '=' . $val . '&';
        }
        $temp_str .= 'timestamp=' . $timestamp . '&';
        $sign_str = $temp_str;
        $temp_str .= 'secretKey=' . $secretKey;
        $sign = sha1($temp_str);

        $url = "http://api.test2.logibeat.com/openapi/common/Bs/api/openApi/getConsign.htm?" . $sign_str;
        //$url = "http://api.logibeat.com/openapi/common/Bs/api/openApi/getConsign.htm?" . $sign_str ;
        $url .= "sign=" . $sign;
        Log::write($url, 'notice');

        $client = new Client();
        $res = $client->request('POST', $url);
        $body = $res->getBody();
        $content = $body->getContents();
        $rev = json_decode($content, true);
        if ($rev['suc'] == true) {
            $data = json_decode($rev['data'], true);
        } else {
            $data = $rev;
        }
        $i_count = count($data);
        echo '共计: ' . $i_count . ' 条单据信息' . '</br>';

        // 检查,保存 单据是否已经写入
        return $data;
    }

    public function index() {
        $beg_date = input('beg_date');
        $end_date = input('end_date');
        if(empty($beg_date) || empty($end_date)) {
            echo lang('请指定查询的开始与结束日期');
            return 0;
        }
        $int = date_day_between($beg_date, $end_date);
        $need_num = ceil($int / 3);
        $all_data = [];
        for($i = 1; $i <= $need_num; $i++) {
            $temp_date = date("Y-m-d", strtotime('+2 day', strtotime($beg_date)));
            if(strtotime($temp_date) > strtotime($end_date)) {
                $temp_date = date("Y-m-d", strtotime($end_date));
            }
            // 获取本次数据
            echo '第 ' . $i . ' 次查询: 日期: ' . $beg_date . ' : ' . $temp_date . '<br/>';
            $data = $this->get_data($beg_date, $temp_date);
            $all_data = array_merge($all_data, $data);
            $beg_date = date("Y-m-d", strtotime('+1 day', strtotime($temp_date)));
        }

        print_r($all_data);
        Log::write($all_data, 'notice');

        return '';
    }

}
